/**
 * 
 */
package forumTransform.forumTransformID;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

import org.apache.http.client.ClientProtocolException;

/**
 * @author Dan
 *
 */
public class WordpressJSON extends Blog {
	 private Integer found;
	 private List<WPost> posts;
	 private List<WComment> comments;
	 TreeSet<String>	users = new TreeSet<String>();
	 
	 private List<Utterance> utterances = new ArrayList<Utterance>();
	 private HashMap<String,ParticipationLog> plList = new HashMap<String, ParticipationLog>();
	 
	 public Integer getFound() {
		return found;
	}
	public void setFound(Integer found) {
		this.found = found;
	}
	public List<WPost> getPosts() {
		return posts;
	}
	public void setPosts(List<WPost> posts) {
		this.posts = posts;
	}
	
	public WPost getPostById(Double id){
		for (WPost post : posts) {
			if(post.getID().compareTo(id) == 0)
				return post;
		}
		return null;
	}
	
	public WordpressJSON() {
		super();
	}
	
	public void populateBlog(){
		int pages 	 = found/100;
		int overflow = found%100;
		if (overflow >0)
			pages ++;
		System.out.println("Found: "+found+"posts and "+pages+" pages");
		//WordpressJSON b = null;
		for (int i = 0; i < pages; i++) {
			try {
				//b = new WordpressJSON();
				//b = Utils.getInfo(getBlogId(), 100, i*100);
				this.addPosts(Utils.getInfo(getBlogId(), 100, i*100));
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		 
	}
	

	public void populateComments(){
		for (Iterator it = this.getPosts().iterator(); it.hasNext();) {
			WPost post = (WPost) it.next();
			WordpressJSON blog = Utils.createBlogForComments(getBlogId(), post.getID().toString());
			int pages 	 = blog.getFound()/100;
			int overflow = blog.getFound()%100;
			if (overflow >0)
				pages ++;
			for (int i = 0; i < pages; i++) {
				try {
					blog = Utils.getInfoComments(blog.getBlogId(), post.getID().toString(), 100, i*100);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			this.addComments(blog);
			if(blog.getComments()!=null)
				post.getComments().addAll(blog.getComments());
		}
	}
	
	
	public void populateComments2(){

			WordpressJSON blog = Utils.createBlog(getBlogId(),true);
			int pages 	 = blog.getFound()/100;
			int overflow = blog.getFound()%100;
			if (overflow >0)
				pages ++;
			for (int i = 0; i < pages; i++) {
				try {
					//blog = Utils.getInfoComments2(getBlogId(), 100, i*100);
					this.addComments(Utils.getInfoComments2(getBlogId(), 100, i*100));
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
	}


	public void addPosts(WordpressJSON wJson){
		if(wJson.getPosts() !=null){
			if(this.posts == null)
				this.posts = new ArrayList<WPost>();
			this.posts.addAll(wJson.getPosts());
		}
	}
	
	public void addComments(WordpressJSON wJson){
		if(wJson.getComments() !=null){
			if(this.comments == null)
				this.comments = new ArrayList<WComment>();
			this.comments.addAll(wJson.getComments());	
		}
	}
	
	public List<WComment> getComments() {
		return comments;
	}
	public void setComments(List<WComment> comments) {
		this.comments = comments;
	}
	
	public void process(){

//		for (WComment comment : comments) {
//			System.out.println("id:"+comment.getID()+" cId:"+comment.getPost().getID()+" ");
//		}
		users.addAll(getAllUsers());
	}
	
	private Collection<String> getAllUsers() {
		TreeSet<String>	result = new TreeSet<String>();
		HashMap<Double,Utterance> postHM =new HashMap<Double, Utterance>();
		double i =0;
		for (WPost post : posts) {

			String postAuthorId = getAuthorName(post.getAuthor());
			result.add(postAuthorId);
			
			Utterance parent = new Utterance(++i, 0 , postAuthorId, null, post.getDate(), this.getBlogId());
			System.out.println("Process post no "+i + "out of "+posts.size());
			parent.setPostId(post.getID());
			parent.setText(Utils.escapeText(post.getContent()));
			parent.setPostAuthorId(postAuthorId);
			utterances.add(parent);
			addParticipationLog(parent);
			parent.setUserId(postAuthorId);
			postHM.put(parent.getPostId(), parent);
		}
		for (WComment comment : comments) {
			String commAuthorId = getAuthorName(comment.getAuthor());//comment.getAuthor().getName()+"-"+comment.getAuthor().getEmail(); 
			result.add(commAuthorId);
			Utterance parent = null;
			if(comment.getPost()== null || comment.getPost().getID()==null)
				continue;
			parent  = postHM.get(comment.getPost().getID());
			if(parent == null || parent.getId() == 0d) continue;
			Utterance child = new Utterance(++i, parent.getId() , commAuthorId, parent.getPostAuthorId(), comment.getDate(), this.getBlogId());
			System.out.println("Process comment no "+i + "out of "+comments.size());
			child.setText(Utils.escapeText(comment.getContent()));
			utterances.add(child);
			addParticipationLog(child);
		}
		
		return result;
	}
	
	public String getAuthorName(WAuthor a){
		String result = a.getName().toLowerCase().replaceAll(" ", "_");
		if(a.getEmail() != null && "".compareTo(a.getEmail())!=0 && "false".compareTo(a.getEmail())!=0)
			result+=a.getEmail();
		if(a.getID() != null && "".compareTo(a.getID())!=0 && "0".compareTo(a.getID())!=0)
			result+=a.getID();
		return Utils.escapeText(result);
		
	}
	
	public void exportPolyCafe() throws IOException {
		FileOutputStream fop = null;
		File file;
        String filename = "polycafe_p"+users.size()+"_u"+utterances.size()+"_"+this.getBlogId().replaceAll(" ", "-");
        String extension = ".xml";
        file = new File("C:\\Users\\Dan\\workspace\\forumTransformID\\out\\"+filename+extension);
		fop = new FileOutputStream(file);
		// if file doesn't exists, then create it
		if (!file.exists()) {
			file.createNewFile();
		}

        String content    = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        content += "<Dialog team=\""+getBlogId()+"\">\n";
        content += "<Participants>\n";
        for (Iterator<String> it = users.iterator(); it.hasNext();) {
            String u = (String) it.next();
            content += "\t<Person nickname=\""+u+"\" />\n";
        }
        content +=    "</Participants>\n";
        content +=    "<Topics>\n";
        for (WPost post : posts) {
        	content +=    "\t<Topic>";
            content +=    Utils.escapeText(post.getTitle());
            content +=    "</Topic>\n";
		}
        content +=    "</Topics>\n";
        content +=    "<Body>\n";
        byte[] contentInBytes = content.getBytes();
        fop.write(contentInBytes);
		fop.flush();
       long i=0;
       StringBuffer sb = new StringBuffer();
        for (Iterator<Utterance> it = utterances.iterator(); it.hasNext();) {
            Utterance utt = (Utterance) it.next();
            //if( !(u.getUserId() == null || u.getRefUserId()== null))
                //content += u.getUserId()+" "+u.getRefUserId()+"\n";
            System.out.println("Exporting utt: "+ (++i) + " out of"+utterances.size());
            sb.delete(0, sb.length());
            sb.append("\t<Turn nickname=\""+utt.getUserId()+"\" >\n");
            sb.append( "\t\t<Utterance genid=\""+utt.getId()+"\" ref=\""+utt.getRefId()+"\" time=\""+utt.getUtteranceTime()+"\">");
            sb.append( Utils.escapeText(utt.getText()));
            sb.append( "</Utterance>\n");
            sb.append( "\t</Turn>\n");
            contentInBytes = sb.toString().getBytes();
            fop.write(contentInBytes);
    		fop.flush();
        }

        sb.delete(0, sb.length());
        sb.append( "</Body>\n");
        sb.append( "</Dialog>\n");
        contentInBytes = sb.toString().getBytes();
        fop.write(contentInBytes);
		fop.flush();
		// get the content in bytes
		//byte[] contentInBytes = content.getBytes();
//		fop.write(contentInBytes);
	//	fop.flush();
		fop.close();
       
    }
	
//	
//	public void exportPolyCafe2() {
//        String content    = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
//        content += "<Dialog team=\""+getBlogId()+"\">\n";
//        content += "<Participants>\n";
//        for (Iterator<String> it = users.iterator(); it.hasNext();) {
//            String u = (String) it.next();
//            content += "\t<Person nickname=\""+u+"\" />\n";
//        }
//        content +=    "</Participants>\n";
//        content +=    "<Topics>\n";
//        for (WPost post : posts) {
//        	content +=    "\t<Topic>";
//            content +=    Utils.escapeText(post.getTitle());
//            content +=    "</Topic>\n";
//		}
//        content +=    "</Topics>\n";
//        content +=    "<Body>\n";
//       long i=0;
//        for (Iterator<Utterance> it = utterances.iterator(); it.hasNext();) {
//            Utterance utt = (Utterance) it.next();
//            //if( !(u.getUserId() == null || u.getRefUserId()== null))
//                //content += u.getUserId()+" "+u.getRefUserId()+"\n";
//            System.out.println("Exporting utt: "+ (++i) + " out of"+utterances.size());
//            content += "\t<Turn nickname=\""+utt.getUserId()+"\" >\n";
//            content += "\t\t<Utterance genid=\""+utt.getId()+"\" ref=\""+utt.getRefId()+"\" time=\""+utt.getUtteranceTime()+"\">";
//            content += Utils.escapeText(utt.getText());
//            content += "</Utterance>\n";
//            content += "\t</Turn>\n";
//        }
//       
//        content += "</Body>\n";
//        content += "</Dialog>\n";
//       
//        ResultFileWriter outWriter        = new ResultFileWriter("polycafe_p"+users.size()+"_u"+utterances.size()+"_"+this.getBlogId().replaceAll(" ", "-"), content,".xml");
//        outWriter.persist();
//       
//    }

	
	public TreeSet<String> getUsers() {
		return users;
	}
	public void setUsers(TreeSet<String> users) {
		this.users = users;
	}
	public List<Utterance> getUtterances() {
		return utterances;
	}
	public void setUtterances(List<Utterance> utterances) {
		this.utterances = utterances;
	}
	
	public void addParticipationLog(Utterance u){
		
		//check if it is existing user
		if( plList.containsKey(u.getUserId()) ){
			ParticipationLog log = plList.get(u.getUserId());
			log.addLog(u, true);
		}
		else{
			plList.put(u.getUserId(), new ParticipationLog(u,true));
		}
		
		//check if the ref user exist
		if( plList.containsKey(u.getRefUserId()) ){
			ParticipationLog log = plList.get(u.getRefUserId());
			log.addLog(u, false);
		}
		else{
			plList.put(u.getRefUserId(), new ParticipationLog(u,false));
		}
		
	}
	
	public String exportCSV(){
		String result = "";
		result +="User,No_Sent_Messages,No_Receive_Messages,No_Sent_Chars,No_Receive_Chars, No_Topics, No_Users_Receive, No_Users_Sent\n";
		for (Iterator<ParticipationLog> it = this.plList.values().iterator(); it.hasNext();) {
			ParticipationLog log = (ParticipationLog) it.next();
			result	+=	log.exportCSV();
		}
		return result;
	}
	
	public HashMap<String, ParticipationLog> getPlList() {
		return plList;
	}
	public void setPlList(HashMap<String, ParticipationLog> plList) {
		this.plList = plList;
	}
	
}
